package terra.model.object.ai;

import terra.managers.ThreadPoolManager;
import terra.model.object.action.ActionFear;
import terra.model.object.action.ActionMove;
import terra.model.object.action.ActionWait;
import terra.model.object.interfaces.Attacker;
import terra.model.runnable.MapIndexChecker;
import terra.util.MathUtil;

public class FlyAI extends AbstractAI {

	private static final long serialVersionUID = -2859378917221413850L;

	public int RND_MOVE_CHANCE = 100;
	public int DISTANCE = 360;
	public boolean onGround = true;

	@Override
	public void update(int delta) {
		if (getOwner().isDead())
			return;
		getCurrentAction().update(delta);
		if (getCurrentAction().ended)
			think();

		if (fear > 0)
			if (System.currentTimeMillis() - lastFeared > 10000) {
				fear--;
				lastFeared = System.currentTimeMillis();
			}
	}

	@Override
	public void think() {
		if (MathUtil.rnd.nextInt(RND_MOVE_CHANCE) == 0) {
			int distance = -100 + MathUtil.rnd.nextInt(200);
			setCurrentAction(new ActionMove(this, distance, getOwner()
					.isAllowJump()));
			if (distance < 0)
				getOwner().setLeft(true);
			else
				getOwner().setLeft(false);
		} else
			setCurrentAction(new ActionWait(this, MathUtil.rnd.nextInt(250)));
		ThreadPoolManager.getInstance().scheduleGeneral(
				new MapIndexChecker(getOwner(), getOwner().getMapIndex()),
				1000L);
	}

	@Override
	public void isAttacked(Attacker attacker) {
		super.isAttacked(attacker);
		// TODO количество очков страха должно добавляться
		// по формуле ?!
		fear += 1;
		// если страх превышает допустимый - пускаемся в бегство
		if (fear >= maxFear) {
			setCurrentAction(new ActionFear(this, attacker, getOwner()
					.isAllowJump()));
			System.out.println("fear");
		}
		lastFeared = System.currentTimeMillis();
	}
}
